//
//  LHOAuthViewController.m
//  OCSinaWeibo
//
//  Created by LiHong on 15/11/2.
//  Copyright © 2015年 LiHong. All rights reserved.
//

#import "LHOAuthViewController.h"
#import "SVProgressHUD.h"
#import "LHHttpTool.h"
#import "AFNetworking.h"
#import "LHAccount.h"
#import "LHHomeTableViewController.h"
@interface LHOAuthViewController ()<UIWebViewDelegate>

@property (nonatomic,strong)UIWebView *webView;

@end

@implementation LHOAuthViewController

- (void)loadView{
    [super loadView];
    self.view = self.webView;
    self.webView.delegate = self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"新浪微博";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(close)];
    NSString *oauthUrl = [NSString stringWithFormat:@"https://api.weibo.com/oauth2/authorize?client_id=%@&response_type=code&redirect_uri=%@",client_id,redirect_uri];
    
    NSURL *url = [NSURL URLWithString:oauthUrl];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
}

#pragma mark - UIWebViewDelegate代理方法
- (void)webViewDidStartLoad:(UIWebView *)webView{
    [SVProgressHUD showWithStatus:@"正在玩命加载..." maskType:SVProgressHUDMaskTypeBlack];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [SVProgressHUD dismiss];
}


/// 访问连接是否能加载
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
 //   NSString *urlString = [request URL].absoluteString;
    
    if ([[request URL].absoluteString hasPrefix:redirect_uri]) {
    //    NSString *codeString = @"code=";
                                            //将字符串切割成数组
        NSString *code = [request.URL.query componentsSeparatedByString:@"="][1];
       // NSString *code = [request.URL.query substringFromIndex:(codeString)]
        NSLog(@"code = %@",code);
        [self accessTokenWithCode:code];
        return YES;
    }
    return YES;
}
#pragma mark - 获取accessToken
- (void)accessTokenWithCode:(NSString *)code{
    NSString *urlString = @"https://api.weibo.com/oauth2/access_token";
    NSDictionary *parameters = @{
                                 @"client_id" : client_id,
                                 @"client_secret": client_secret,
                                 @"grant_type": grant_type,
                                 @"code": code,
                                 @"redirect_uri": redirect_uri
                                 };
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    // 设置二进制处理方式
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:urlString parameters:parameters success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        LHAccount *account = [LHAccount objectWithJSONData:responseObject];
   //     NSLog(@"%@",account.avatar_large);
        if (account.access_token) {
            [self loadUserInfo];
            [account saveAccountToSandBox];
          //  LHHomeTableViewController *homeVc = [[LHHomeTableViewController alloc]init];
          //  [UIApplication sharedApplication].keyWindow.rootViewController = homeVc;
        }
        
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        NSLog(@"error = %@",error);
        [self netError:@"获取授权失败"];
    }];
}

- (void)loadUserInfo{
    LHAccount *account = [LHAccount shareAccount];
    NSString *access_token = account.access_token;
    
    NSString *urlString = @"https://api.weibo.com/2/users/show.json";
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSDictionary *parameters = @{@"access_token" : access_token};
    
    
    [manager GET:urlString parameters:parameters success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        LHAccount *account = [LHAccount objectWithJSONData:responseObject];
        NSLog(@"%@",account.avatar_large);
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        [self netError:@"获取用户信息失败"];
    }];
    
}

- (void)netError:(NSString *)msg{
    [SVProgressHUD showErrorWithStatus:msg];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self close];
    });
}
/// 取消按钮点击事件
- (void)close{
    [SVProgressHUD dismiss];
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 懒加载
- (UIWebView *)webView{
    if (!_webView) {
        _webView = [[UIWebView alloc]init];
    }
    return _webView;
}

@end
